package strategy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import core.CharCount;
import core.OpenedFile;

public class KeyStatistic implements AlgorithmInteface {

	private HashMap<Character, CharCount> _statistic;
	private OpenedFile _file = null;
	private String text;

	public KeyStatistic(OpenedFile file) {
		_statistic = new HashMap<Character, CharCount>();
		_file = file;
		init();
		doStatistic();
	}
	
	public KeyStatistic(String text) {
		_statistic = new HashMap<Character, CharCount>();
		this.text = text;
		init();
		doStatistic();
	}

	public void doStatistic() {
		String fileContent;
		if (_file == null) {
			fileContent = text; 
		} else {
			fileContent = _file.getStringFormat();
		}
		System.out.println("file: " + fileContent);
		fileContent = fileContent.toUpperCase();
		for (int i = 0; i < fileContent.length(); i++) {
			if (fileContent.charAt(i) >= 'A' && fileContent.charAt(i) <= 'Z') {
				CharCount temp = _statistic.get(fileContent.charAt(i));
				temp.inc();
			}
		}
	}
	
	public List<CharCount> sort() {
		List<CharCount> values = new ArrayList<>(_statistic.values());

		// Sorting
		for (int i = 0; i < values.size(); i++) {
			int max = values.get(i).get_count();
			int pos = i;
			for (int j = i+1; j < values.size(); j++){
				if (values.get(j).get_count() > max) {
					max = values.get(j).get_count();
					pos = j;
				}
			}
			CharCount temp = values.get(i);
			values.set(i, values.get(pos));
			values.set(pos, temp);
		}
		
		return values;
	}
	
	public HashMap<Character, CharCount> getStatistic() {
		return _statistic;
	}

	private void init() {
		for (char c = 'A'; c <= 'Z'; c++) {
			_statistic.put(c, new CharCount(c, 0));
		}		
	}

	public String toString() {
		return _statistic.toString();
	}
	
	@Override
	public void decrypt() {
		doStatistic();
	}

	@Override
	public void encrypt() {
		doStatistic();
	}

	@Override
	public void update() {
		doStatistic();
	}

	@Override
	public void autoDecrypt() {
		// TODO Auto-generated method stub
		
	}
	
}
